package com.hengxinguotong.zhihuichengjian.ui.document;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Document;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectListPop;
import com.lidroid.xutils.http.RequestParams;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 文档添加以及文档详情界面
 * Created by liux on 2017/3/7.
 */

public class AddDocumentActivity extends BaseActivity implements AualityTestAddPicAdapter.OnRecyclerViewClickListener {
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_test)
    HXTextView saveTest;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.name_ev)
    HXEditTextView nameEv;
    @BindView(R.id.check_date_rl)
    RelativeLayout checkDateRl;
    @BindView(R.id.type_tv)
    HXTextView typeTv;
    @BindView(R.id.no_pic_tv)
    HXTextView noPicTv;
    @BindView(R.id.add_pic_rv)
    RecyclerView addPicRv;
    @BindView(R.id.remark_etv)
    HXEditTextView remarkEtv;
    @BindView(R.id.main_sl)
    ScrollView mainSl;
    private AualityTestAddPicAdapter aualityTestAddPicAdapter;
    private List<String> paths;
    private List<String> minPaths;
    private int type = -1;
    private Document document;
    private SelectListPop mSelectListPop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_document);
        ButterKnife.bind(this);
        document = (Document) getIntent().getSerializableExtra("document");
        initView();
    }

    private void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        addPicRv.setLayoutManager(linearLayoutManager);
        if (document != null) {
            saveTest.setVisibility(View.GONE);
            tvTitleName.setText("文档详情");
            Utils.setEditTextViewUnable(document.getName(), nameEv);
            Utils.setEditTextViewUnable(document.getRemark(), remarkEtv);
            Utils.setEditTextViewUnable(DocumentManagementActivity.getDocumentTypeById(document.getType()), typeTv);
            if (document.getFileList().size() == 0) {
                noPicTv.setVisibility(View.VISIBLE);
                addPicRv.setVisibility(View.GONE);
            } else {
                addPicRv.setLayoutManager(linearLayoutManager);
                paths = document.getFileList();
                aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, false);
                addPicRv.setAdapter(aualityTestAddPicAdapter);
            }
        } else {
            tvTitleName.setText("新增文档");
            paths = new ArrayList<String>();
            paths.add(Utils.ADDPIC);
            aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, true);
            addPicRv.setAdapter(aualityTestAddPicAdapter);
        }

    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            if (document != null) {
                TaskBigImgActivity.startActivity(AddDocumentActivity.this, (ArrayList<String>) paths, position);
            } else {
                paths.remove(position);
                aualityTestAddPicAdapter.notifyDataSetChanged();
            }
        }
    }


    private void addDocument() {
        if (!checkContent()) {
            return;
        }

        RequestParams params = new RequestParams();
        params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));
        params.addBodyParameter("createBy", SPUtil.getString(this, "userId"));
        params.addBodyParameter("type", type + "");
        params.addBodyParameter("name", nameEv.getEditableText().toString());
        if (!Utils.isEmpty(remarkEtv.getEditableText().toString())) {
            params.addBodyParameter("remark", remarkEtv.getEditableText().toString());
        }
        for (int i = 0; i < minPaths.size(); i++) {
            params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
        }

        Utils.requestData(getResources().getString(R.string.loading), this, "/dataManagement/save/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                showToast("添加成功");
                setResult(1);
                finish();
            }

            @Override
            public void onFailure(String json) {

            }
        });

    }

    private void getMinImage() {
        if (!checkContent()) {
            return;
        }

        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), this);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    addDocument();
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            addDocument();
        }

    }

    private void showSelectPop() {
        final String[] types = new String[DocumentManagementActivity.documentTypeList.size()];
        for (int i = 0; i < types.length; i++) {
            types[i] = DocumentManagementActivity.documentTypeList.get(i).getName();
        }
        mSelectListPop = new SelectListPop(this, R.layout.dialog_select_sex, types, new SelectListPop.OnDirListPopItemClicked() {
            @Override
            public void onPopItemClick(int position, String name) {
                type = DocumentManagementActivity.documentTypeList.get(position).getValue();
                typeTv.setText(types[position]);
            }
        });
        mSelectListPop.setFocusable(true);
        mSelectListPop.setOutsideTouchable(true);
        mSelectListPop.setBackgroundDrawable(getResources().getDrawable(R.color.color_transparent));
        mSelectListPop.update();
        mSelectListPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        if (mSelectListPop.isShowing()) {
            mSelectListPop.dismiss();
        } else {
            mSelectListPop.showAtLocation(mainSl, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        }
    }

    private boolean checkContent() {
        if (type == -1) {
            showToast("请选择类型");
            return false;
        }

        if (Utils.isEmpty(nameEv.getEditableText().toString())) {
            showToast("请填写名称");
            return false;
        }

        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && data != null) {
            paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            paths.add(Utils.ADDPIC);
            if (aualityTestAddPicAdapter != null) {
                aualityTestAddPicAdapter.setPaths(paths);
            }
        }
    }

    @OnClick({R.id.iv_back, R.id.save_test, R.id.type_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_test:
                getMinImage();
                break;
            case R.id.type_tv:
                if (DocumentManagementActivity.documentTypeList != null && DocumentManagementActivity.documentTypeList.size() > 0) {
                    showSelectPop();
                }
                break;
        }
    }
}
